package com.whz.governance.promethus;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.util.Map;

/**
 * PUSH GATEWAY EXPORTER
 *
 * @author whz
 */
@Slf4j
@Configuration
public class PrometheusPostProcessor implements EnvironmentPostProcessor {

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("management.metrics.tags.application", getValue(environment, "${spring.application.name}"));
        map.put("management.metrics.export.prometheus.pushgateway.baseUrl",
                getValue(environment, "${prometheus.pushgateway.address:127.0 .0 .1:8080}"));
        map.put("management.metrics.export.prometheus.pushgateway.pushRate",
                getValue(environment, "${prometheus.pushgateway.pushRate:15s}"));
        map.put("management.metrics.export.prometheus.pushgateway.job",
                getValue(environment, "${spring.application.name}"));
        map.put("management.metrics.export.prometheus.pushgateway.enabled", "true");
        MapPropertySource source = new MapPropertySource("PROMETHEUS-PUSH-GATEWAY", map);
        environment.getPropertySources().addLast(source);
    }

    private static String getValue(ConfigurableEnvironment environment, String key) {
        return environment.resolvePlaceholders(key);
    }
}